﻿
using SIG.Model;
using SIG.Data.UnitOfWork;
using SIG.Infrastructure.Logging;
using SIG.Data;
using System;
using System.Linq;
using System.Collections.Generic;
using SIG.Infrastructure.Cache;
using SIG.Resources;

namespace SIG.Repository
{
    public class LogRepository : Repository<Log>, ILogRepository
    {
        IMainBCUnitOfWork _unitOfWork;
        private ICacheService _cacheService;
        /// <summary>
        /// Create a new instance
        /// </summary>
        /// <param name="unitOfWork">Associated unit of work</param>
        /// <param name="logger">Associated logger</param>


        public LogRepository(IMainBCUnitOfWork unitOfWork,  ICacheService cacheService)
            : base(unitOfWork)
        {
            if (unitOfWork == (IMainBCUnitOfWork)null)
                throw new ArgumentNullException("unitOfWork");
            if (cacheService == (ICacheService)null)
                throw new ArgumentNullException("cacheService");
            this._unitOfWork = unitOfWork;
            this._cacheService = cacheService;
        }

        public int SearchLogsCount(DateTime? startDate, DateTime? expireDate, string level)
        {
            var logs = this.GetAllElements();

            if (startDate!=null)
            {               
                logs = logs.Where(l => l.Date >= startDate);
            }

            if (expireDate!=null)
            {                
                logs = logs.Where(l => l.Date <= expireDate);
            }

            if (!string.IsNullOrEmpty(level))
                logs = logs.Where(l => l.Level == level);

            var result = logs.Count();

            return result;
        }

        public IEnumerable<Log> SearchLogs(int pageIndex, int pageSize, DateTime? startDate, DateTime? expireDate,
            string level)
        {
            var logs = this.GetAllElements();

            if (startDate != null)
            {
                logs = logs.Where(l => l.Date >= startDate);
            }

            if (expireDate != null)
            {
                logs = logs.Where(l => l.Date <= expireDate);
            }

            if (!string.IsNullOrEmpty(level))
                logs = logs.Where(l => l.Level == level);

            var result = logs
                .OrderByDescending(l => l.Date)
                .Skip(pageIndex * pageSize).Take(pageSize).AsEnumerable();

            return result;
        }



        public int RemoveAll()
        {
          return  _unitOfWork.ExecuteCommand("Delete from Logs");  
        }
    }
}
